using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.AddressableAssets.Settings;
using UnityEngine;

namespace AddressablesTool
{
    /// <summary>
    /// Prefab依赖分析窗口
    /// </summary>
    public class PrefabDependencyWindow : EditorWindow
    {
        private List<GameObject> selectedPrefabs = new List<GameObject>();
        private List<Object> dependencies = new List<Object>();
        private Vector2 prefabScrollPos;
        private Vector2 dependencyScrollPos;
        private string targetGroupName = "PrefabDependencies";
        private bool showDependencyDetails = true;
        private Dictionary<string, int> typeStats = new Dictionary<string, int>();

        [MenuItem("Tools/Addressables/Prefab Dependency Manager")]
        public static void ShowWindow()
        {
            var window = GetWindow<PrefabDependencyWindow>("Prefab Dependency Manager");
            window.minSize = new Vector2(600, 500);
            window.Show();
        }

        private void OnEnable()
        {
            RefreshSelection();
        }

        private void OnSelectionChange()
        {
            RefreshSelection();
            Repaint();
        }

        private void RefreshSelection()
        {
            selectedPrefabs.Clear();
            dependencies.Clear();
            typeStats.Clear();

            // 获取选中的Prefab
            var selectedObjects = Selection.objects;
            foreach (var obj in selectedObjects)
            {
                if (obj is GameObject gameObject && PrefabUtility.IsPartOfAnyPrefab(gameObject))
                {
                    var prefab = PrefabUtility.GetCorrespondingObjectFromOriginalSource(gameObject);
                    if (prefab != null && !selectedPrefabs.Contains(prefab))
                    {
                        selectedPrefabs.Add(prefab);
                    }
                }
            }

            // 分析依赖
            if (selectedPrefabs.Count > 0)
            {
                dependencies = DependencyAnalyzer.GetDependencies(selectedPrefabs);
                typeStats = DependencyAnalyzer.GetDependencyTypeStats(dependencies);
            }
        }

        private void OnGUI()
        {
            GUILayout.Space(10);

            // 标题
            EditorGUILayout.LabelField("Prefab Dependency Manager", EditorStyles.boldLabel);
            EditorGUILayout.Space();

            // 检查Addressables设置
            if (!AddressablesGroupManager.HasAddressablesSettings())
            {
                EditorGUILayout.HelpBox("Addressables设置未找到。请先创建Addressables设置。", MessageType.Error);

                if (GUILayout.Button("创建Addressables设置"))
                {
                    CreateAddressablesSettings();
                }
                return;
            }

            // 选中的Prefab列表
            DrawPrefabSection();

            EditorGUILayout.Space();

            // 目标组设置
            DrawGroupSettings();

            EditorGUILayout.Space();

            // 依赖资源列表
            DrawDependencySection();

            EditorGUILayout.Space();

            // 操作按钮
            DrawActionButtons();
        }

        private void CreateAddressablesSettings()
        {
            // 创建Addressables设置
            var settings = ScriptableObject.CreateInstance<AddressableAssetSettings>();
            if (settings != null)
            {
                // 设置配置
                settings.name = "AddressableAssetSettings";

                // 确保目录存在
                if (!AssetDatabase.IsValidFolder("Assets/AddressableAssetsData"))
                {
                    AssetDatabase.CreateFolder("Assets", "AddressableAssetsData");
                }

                // 保存设置
                AssetDatabase.CreateAsset(settings, "Assets/AddressableAssetsData/AddressableAssetSettings.asset");
                AssetDatabase.SaveAssets();

                Debug.Log("Addressables设置创建成功");
                RefreshSelection();
            }
            else
            {
                Debug.LogError("Addressables设置创建失败");
            }
        }

        private void DrawPrefabSection()
        {
            EditorGUILayout.LabelField("Selected Prefabs:", EditorStyles.boldLabel);

            if (selectedPrefabs.Count == 0)
            {
                EditorGUILayout.HelpBox("请选中一个或多个Prefab", MessageType.Info);
                return;
            }

            EditorGUILayout.LabelField($"已选中 {selectedPrefabs.Count} 个Prefab");

            prefabScrollPos = EditorGUILayout.BeginScrollView(prefabScrollPos, GUILayout.Height(100));

            foreach (var prefab in selectedPrefabs)
            {
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.ObjectField(prefab, typeof(GameObject), false);

                var path = AssetDatabase.GetAssetPath(prefab);
                if (!string.IsNullOrEmpty(path))
                {
                    var groupName = DependencyAnalyzer.GetAssetGroupName(prefab);
                    if (!string.IsNullOrEmpty(groupName))
                    {
                        EditorGUILayout.LabelField($"在组: {groupName}", GUILayout.Width(120));
                    }
                    else
                    {
                        EditorGUILayout.LabelField("未在Addressables中", GUILayout.Width(120));
                    }
                }

                EditorGUILayout.EndHorizontal();
            }

            EditorGUILayout.EndScrollView();
        }

        private void DrawGroupSettings()
        {
            EditorGUILayout.LabelField("Target Addressables Group:", EditorStyles.boldLabel);

            // 组名输入
            targetGroupName = EditorGUILayout.TextField("Group Name", targetGroupName);

            // 现有组选择
            var groupNames = AddressablesGroupManager.GetAllGroupNames();
            if (groupNames.Count > 0)
            {
                EditorGUILayout.LabelField("Existing Groups:");

                foreach (var groupName in groupNames)
                {
                    if (GUILayout.Button(groupName, EditorStyles.miniButton))
                    {
                        targetGroupName = groupName;
                    }
                }
            }
        }

        private void DrawDependencySection()
        {
            EditorGUILayout.LabelField("Dependencies:", EditorStyles.boldLabel);

            if (dependencies.Count == 0)
            {
                EditorGUILayout.HelpBox("没有找到依赖资源", MessageType.Info);
                return;
            }

            EditorGUILayout.LabelField($"发现 {dependencies.Count} 个依赖资源");

            // 类型统计
            if (typeStats.Count > 0)
            {
                EditorGUILayout.LabelField("资源类型统计:");
                foreach (var stat in typeStats.OrderByDescending(s => s.Value))
                {
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.LabelField(stat.Key, GUILayout.Width(150));
                    EditorGUILayout.LabelField(stat.Value.ToString());
                    EditorGUILayout.EndHorizontal();
                }
            }

            // 依赖详情
            showDependencyDetails = EditorGUILayout.Foldout(showDependencyDetails, "Dependency Details");
            if (showDependencyDetails)
            {
                dependencyScrollPos = EditorGUILayout.BeginScrollView(dependencyScrollPos, GUILayout.Height(200));

                foreach (var dependency in dependencies)
                {
                    if (dependency == null) continue;

                    EditorGUILayout.BeginHorizontal();

                    // 资源对象字段
                    EditorGUILayout.ObjectField(dependency, dependency.GetType(), false);

                    // 状态信息
                    var isInAddressables = DependencyAnalyzer.IsAssetInAddressables(dependency);
                    var groupName = DependencyAnalyzer.GetAssetGroupName(dependency);

                    if (isInAddressables)
                    {
                        var style = groupName == targetGroupName ? EditorStyles.whiteLabel : EditorStyles.label;
                        EditorGUILayout.LabelField($"在组: {groupName}", style, GUILayout.Width(120));
                    }
                    else
                    {
                        EditorGUILayout.LabelField("未在Addressables中", GUILayout.Width(120));
                    }

                    EditorGUILayout.EndHorizontal();
                }

                EditorGUILayout.EndScrollView();
            }
        }

        private void DrawActionButtons()
        {
            EditorGUILayout.BeginHorizontal();

            // 分析按钮
            if (GUILayout.Button("分析依赖", GUILayout.Height(30)))
            {
                RefreshSelection();
            }

            // 添加到组按钮
            GUI.enabled = dependencies.Count > 0 && !string.IsNullOrEmpty(targetGroupName);
            if (GUILayout.Button("添加到组", GUILayout.Height(30)))
            {
                AddDependenciesToGroup();
            }
            GUI.enabled = true;

            EditorGUILayout.EndHorizontal();
        }

        private void AddDependenciesToGroup()
        {
            if (dependencies.Count == 0)
            {
                EditorUtility.DisplayDialog("提示", "没有依赖资源可添加", "确定");
                return;
            }

            if (string.IsNullOrEmpty(targetGroupName))
            {
                EditorUtility.DisplayDialog("错误", "请输入组名", "确定");
                return;
            }

            // 确认对话框
            if (!EditorUtility.DisplayDialog("确认", $"确定要将 {dependencies.Count} 个资源添加到组 '{targetGroupName}' 吗？", "确定", "取消"))
            {
                return;
            }

            // 添加到组
            int successCount = AddressablesGroupManager.AddAssetsToGroup(dependencies, targetGroupName);

            // 保存设置
            AssetDatabase.SaveAssets();

            // 显示结果
            if (successCount > 0)
            {
                EditorUtility.DisplayDialog("完成", $"成功添加 {successCount} 个资源到组 '{targetGroupName}'", "确定");
                RefreshSelection();
            }
            else
            {
                EditorUtility.DisplayDialog("错误", "添加资源失败", "确定");
            }
        }
    }
}